package com.example.weather;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EdgeEffect;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.weather.More.ContactAdapter;
import com.example.weather.data.City;
import com.example.weather.data.CityDao;
import com.example.weather.data.Person;
import com.example.weather.data.WeatherDatabase;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class MsgActivity extends AppCompatActivity {
    private Spinner spinner;
    private List<String> data_list;
    private ArrayAdapter<String> arr_adapter;
    EditText et,phone_num,msg_messge;
    private List<Person>personList=new ArrayList<>();
    ListView lv_phonelist;
    private WeatherDatabase weatherDatabase;
    private CityDao cityDao;
    String[]hotCitys = {"北京","太原","沈阳","重庆","天津","南宁","杭州","武汉","烟台","西安"};
    String url1 = "https://wis.qq.com/weather/common?source=pc&weather_type=observe|index|rise|alarm|air|tips|forecast_24h&province=";
    String url2 = "&city=";
    String message;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msg);
        et=findViewById(R.id.msg_messge_city);
        phone_num=findViewById(R.id.msg_phone);
        lv_phonelist=findViewById(R.id.lv_phone);
        weatherDatabase=WeatherDatabase.getDatabase(this);
        cityDao=weatherDatabase.getCityDao();
        msg_messge=findViewById(R.id.msg_messge_city);
        initview();
    }
    public void addPhoneNumber(View view){//内容提供者
        Uri uri_raw_contact = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri uri_data = Uri.parse("content://com.android.contacts/data");
        ContentResolver resolver=getContentResolver();
        Cursor cursor=resolver.query(uri_raw_contact,new String[]{"contact_id"},null,null,null);
        while(cursor.moveToNext()){
            String id=cursor.getString(0);///获取联系人id
            System.out.println(id+"*****");
            Cursor cursor1=resolver.query(uri_data,new String[]{"mimetype","data1"},"raw_contact_id=?",new String[]{id},null);
            if(cursor1==null) continue;
            Person person=new Person();
            while(cursor1.moveToNext()){
                String mimetype_id=cursor1.getString(0);
                String data1=cursor1.getString(1);
                if(mimetype_id.equals("vnd.android.cursor.item/name")){
                    person.setName(data1);
                }
                if(mimetype_id.equals("vnd.android.cursor.item/phone_v2")||mimetype_id.equals("vnd.android.cursor.item/vnd.com.tencent.mobile.qq.voicecall.profile")){
                    data1=data1.replace(" ","");
                    person.setNumber(data1);
                }
            }
            if(person.getNumber()==null) continue;
            personList.add(person);
            cursor1.close();
        }
        cursor.close();
        if(!personList.isEmpty()){
            for(Person t:personList) System.out.println(t);
        }

        lv_phonelist.setVisibility(View.VISIBLE);
        lv_phonelist.setAdapter(new ContactAdapter(this,personList));
        lv_phonelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Person person=personList.get(i);
                String number=person.getNumber();
                phone_num.setText(number);
                lv_phonelist.setVisibility(View.GONE);
            }
        });
    }
    public void initview(){
        spinner = (Spinner) findViewById(R.id.spinner_test);
        //数据
        data_list = new ArrayList<String>();
        //将data_list的数据变为数据库中的
        data_list=getData();
        //适配器
        arr_adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner.setAdapter(arr_adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String now_city=arr_adapter.getItem(i);
                message=now_city+",";
                String now_provice=GetProvice(now_city);
                String url = url1+now_provice+url2+now_city;
                RequestParams rp = new RequestParams(url);
                x.http().get(rp,new MsgActivity.MyCallBackk());
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
    private List<String>getData(){
        List cityList=new ArrayList<String>();
        List<City>cities=cityDao.findAll();
        if(cities.isEmpty()) {
            for(String tmp_name:hotCitys){
                cityDao.insetCity(new City(tmp_name));
                System.out.println("插入了城市"+tmp_name+"\n");
            }
            cities=cityDao.findAll();
        }
        for (City c : cities) {
            cityList.add(c.getName());
            System.out.println(c);
        }
        return cityList;
    }

    public  void msg_on(View view){
        Intent intent=new Intent(this,MsgModelActivity.class);
        intent.putExtra("msg",et.getText().toString().trim());
        startActivityForResult(intent,0);
    }
    public void msg_back(View view){
        Intent intent=new Intent(this,MoreActivity.class);
        startActivityForResult(intent,0);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCoder, @Nullable Intent data){
        if(resultCoder==1){
            String message=data.getStringExtra("msg");
            et.setText(message);
        }
        super.onActivityResult(requestCode,resultCoder,data);
    }
    public void sendMsg(View view){
        Uri sms=Uri.parse("smsto:"+phone_num.getText().toString().trim());
        Intent intent=new Intent();
        intent.setAction(Intent.ACTION_SENDTO);
        intent.setData(sms);
        intent.putExtra("sms_body",et.getText().toString().trim());
        startActivity(intent);
    }
    public class MyCallBackk implements Callback.CommonCallback<String>{

        @Override
        public void onSuccess(String result) {
            //        解析并展示数据
            try {
                parseShowData(result);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println(result);
            System.out.println("SUCCESS");
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            System.out.println("***"+ex);
            System.out.println("ERROR");
        }

        @Override
        public void onCancelled(CancelledException cex) {

        }

        @Override
        public void onFinished() {
            System.out.println("完成");
        }
    }
    private void parseShowData(String result) throws ParseException {
//        使用gson解析数据
        WeatherBean weatherBean = new Gson().fromJson(result, WeatherBean.class);
        WeatherBean.DataBean resultsBean = weatherBean.getData();
        WeatherBean.DataBean.IndexBean index = resultsBean.getIndex();
        System.out.println(result);
//        获取今日天气情况
        WeatherBean.DataBean.ObserveBean todayDataBean = resultsBean.getObserve();
        message=message+"天气："+todayDataBean.getWeather_short()+",";
        message=message+"风向 "+"西南风"+todayDataBean.getWind_power()+"级,";
        message=message+"当前温度："+todayDataBean.getDegree()+"°C";
        msg_messge.setText(message);
        System.out.println(message+"*****");
    }


    private String GetProvice(String city) {
        String[]Citys = {"北京","上海","广东省 广州","广东省 深圳","广东省 珠海","广东省 佛山",
                "江苏省 南京","江苏省 苏州","福建省 厦门","湖南省 长沙","四川省 成都","福建省 福州","浙江省 杭州",
                "湖北省 武汉","山东省 烟台","陕西省 西安","山西省 太原","辽宁省 沈阳","重庆","天津","广西省 南宁"};
        String provice=null;
        for(int i=0;i<Citys.length;i++){
            if(Citys[i].contains(city)){
                if(Citys[i].split(" ").length>1)
                {   provice =Citys[i].split(" ")[0];
                }
                else
                {
                    provice = Citys[i].split(" ")[0];
                }
                break;
            }
        }
        return provice;
    }











}